<template>
  <div>
    <Teleport to="#app">
      <div v-if="show" id="RightMenu" class="RightMenu">
        <div @click.native.right="e => e.preventDefault()" id="rightMenuContent" ref="rightMenuContent"
          class="rightMenuContent">
          <slot v-if="rightMenuContent" :to="rightMenuContent" />
        </div>
      </div>
    </Teleport>
  </div>
</template>

<script setup lang='ts'>
import { CSSProperties } from 'vue';
const rightMenuContent = ref()
const props = defineProps<{
  event: MouseEvent | undefined
}>()
const cancelMenu = (e: MouseEvent) => {
  if (window.RightMenu.contains(e.target as Node)) {
    return
  }
  if (e.button === 2) {
    if (e.target !== props.event?.target) {
      show.value = false
    }
    const menuContent = (window.RightMenu?.style as CSSProperties)!;
    menuContent.top = `${e.clientY}px`
    menuContent.left = `${e.clientX}px`
  }
  if (e.button === 0) {
    show.value = false
  }
}
const rightMenuHandler = () => {
  document.addEventListener('mousedown', cancelMenu);
  const menuContent = (window.RightMenu?.style as CSSProperties)!
  menuContent.top = `${props.event?.clientY}px`
  menuContent.left = `${props.event?.clientX}px`
}
const emit = defineEmits<{
  (e: 'update:show', value: boolean): void
}>()
const show = defineModel('show', { default: false })
watch(() => show.value, async (value) => {
  emit('update:show', value)
  document.body.style.cursor = 'default'
  if (!value) {
    document.body.style.cursor = 'auto'
    document.removeEventListener('mousedown', cancelMenu);
    return
  }
  props.event!.preventDefault();
  (props.event!.target! as any).oncontextmenu = (e: Event) => {
    e.preventDefault()
  }
  await nextTick();
  rightMenuHandler()
})
</script>

<style lang="scss" scoped>
.RightMenu {
  position: absolute;
  z-index: 999;

  .RightMenuModel {
    position: absolute;
    width: 100vw;
    height: 100vh;
    background: unset;
    border: unset;

    #RightMenuModel {
      width: 100%;
      height: 100%;
    }
  }

  .rightMenuContent {}
}
</style>